package com.ly.lw.styledo.fragment;


import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.widget.AdapterView;
import android.widget.RadioGroup;

import com.alibaba.fastjson.JSONObject;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshStaggeredGridView;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.bitmap.PauseOnScrollListener;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.ly.lw.styledo.R;
import com.ly.lw.styledo.adapter.CategoryInfoAdapter;
import com.ly.lw.styledo.beancategoryinfo.CInfoList;
import com.ly.lw.styledo.beancategoryinfo.CInfoResult;
import com.ly.lw.styledo.beancategoryinfo.CategoryInfoResult;
import com.ly.lw.styledo.config.UrlCategory;
import com.ly.lw.styledo.ui.CategorySecondInfoActivity;
import com.ly.lw.styledo.utils.FileUtils;

import java.util.ArrayList;
import java.util.List;

import etsy.android.grid.StaggeredGridView;

/**
 * @author 王学玲
 *         A simple {@link Fragment} subclass.
 *         分类-推荐-详情-碎片
 */
//@EFragment(R.layout.fragment_category_info)
public class CategoryInfoFragment extends Fragment implements PullToRefreshBase.OnRefreshListener2<StaggeredGridView>, AdapterView.OnItemClickListener {
    //控件、数据源、适配器
//    @ViewById(R.id.category_info_ptrsgv)
    @ViewInject(R.id.category_info_ptrsgv)
    PullToRefreshStaggeredGridView ptrsgv;

    private ArrayList<CInfoList> datas;
    private CategoryInfoAdapter adapter;

    private BitmapUtils bitmapUtils;
    private etsy.android.grid.StaggeredGridView staggeredGridView;

    private ViewHolder vh;

    private int cateno;
    private String type = "03";

    private RadioGroup rgs;

    /**
     * 是否清除数据
     */
    private boolean isClear;


    public CategoryInfoFragment() {
        // Required empty public constructor
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            cateno = getArguments().getInt("cateno");
        }
        initBitmap();
    }


    public static CategoryInfoFragment newInstance(int cateno) {
        CategoryInfoFragment fragment = new CategoryInfoFragment();
        Bundle args = new Bundle();
        args.putInt("cateno", cateno);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_category_info, container, false);
        ViewUtils.inject(this, view);


        initView(inflater);
        initData();
        return view;
    }

//        @AfterInject
//    public void inject() {
//
//    }

//    代替OnCreat和OnCreatView方法
//    @AfterViews
//    public void init() {
//        if (getArguments() != null) {
//            cateno = getArguments().getInt("cateno");
//        }
//        initView();
//        initData();
//    }

    private void initBitmap() {
        bitmapUtils = new BitmapUtils(getActivity().getApplicationContext(), FileUtils.getImageCache());
        bitmapUtils.configDefaultLoadFailedImage(R.mipmap.ic_logo_small);
        bitmapUtils.configDefaultLoadingImage(R.mipmap.ic_logo_small);

        AlphaAnimation animation = new AlphaAnimation(0.0f, 1.0f);
        animation.setDuration(1000);
        bitmapUtils.configDefaultImageLoadAnimation(animation);
        bitmapUtils.configDefaultBitmapConfig(Bitmap.Config.RGB_565);//设置图片压缩类型

        bitmapUtils.configMemoryCacheEnabled(true);
        bitmapUtils.configDiskCacheEnabled(true);

    }

    private void initView(LayoutInflater inflater) {
        datas = new ArrayList<>();

        initHeadView(inflater);
        initShopUi();
    }

    /**
     * 初始化瀑布流控件相关参数
     */
    private void initShopUi() {
        ptrsgv.setMode(PullToRefreshBase.Mode.BOTH);
        ptrsgv.setOnRefreshListener(this);
        staggeredGridView = ptrsgv.getRefreshableView();
        staggeredGridView.setOnScrollListener(new PauseOnScrollListener(bitmapUtils, false, true));
        staggeredGridView.setOnItemClickListener(this);
        adapter = new CategoryInfoAdapter(datas, getActivity(), bitmapUtils);
        ptrsgv.getRefreshableView().addHeaderView(vh.headView);
        ptrsgv.setAdapter(adapter);
    }

    /**
     * 头
     */
    private void initHeadView(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.category_info_head, ptrsgv, false);
        rgs = (RadioGroup) view.findViewById(R.id.category_info_radiogroup);
        initRgs();
        vh = new ViewHolder(view);
    }


    private void initRgs() {
        rgs.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.category_info_rb_man://人气
                        type = "03";
                        datas.clear();
                        initData();
                        break;
                    case R.id.category_info_rb_new://最新
                        type = "02";
                        datas.clear();
                        initData();
                        break;
                }
            }
        });
    }


    private void initData() {
        HttpUtils httpUtils = new HttpUtils();
        RequestParams params = getRequestParams();
        httpUtils.send(HttpRequest.HttpMethod.POST, UrlCategory.CATEGORY_INFO_URL, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String result = responseInfo.result;
                CategoryInfoResult infoResult = JSONObject.parseObject(result, CategoryInfoResult.class);
                if (infoResult != null) {
                    CInfoResult cInfoResult = infoResult.getResult();
                    List<CInfoList> list = cInfoResult.getList();
                    if (list != null && list.size() > 0) {
                        datas.addAll(list);
                        adapter.notifyDataSetChanged();
                    }

                }
            }

            @Override
            public void onFailure(HttpException e, String s) {

            }
        });
    }


    @Override
    public void onPullDownToRefresh(PullToRefreshBase<StaggeredGridView> refreshView) {
        isClear = true;
        initData();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<StaggeredGridView> refreshView) {
        isClear = false;
        initData();
    }

    public RequestParams getRequestParams() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("cate_no1", "");
        params.addBodyParameter("cate_no2", "");
        params.addBodyParameter("cate_no", cateno + "");
        params.addBodyParameter("sort_type", type);
        params.addBodyParameter("min_price", "");
        params.addBodyParameter("max_price", "");
        params.addBodyParameter("os", "android");
        params.addBodyParameter("page_no", "1");//分页
        params.addBodyParameter("osVersion", "4.1.2");
        params.addBodyParameter("list_size", "60");
        params.addBodyParameter("appVersion", "1.4.6");
        return params;
    }

    /**
     * 瀑布流点击事件
     *
     * @param parent
     * @param view
     * @param position
     * @param id
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//        Toast.makeText(getActivity(), "---->" + position, Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(getActivity(), CategorySecondInfoActivity.class);
        intent.putExtra("prdNo", datas.get(position-1).getPrd_no());
        startActivity(intent);
    }

    private class ViewHolder {
        private View headView;

        public ViewHolder(View headView) {
            this.headView = headView;
        }
    }

}
